package com.zlzlib.libui.util;

import android.view.View;

/**
 * @Desc: 防止点击事件过快
 * @Copyright:
 * @DateTime: 2022/6/9 14:45
 * @Author zlz
 * @Version 1.0
 */
public class ViewClickDelay implements View.OnClickListener {
    //全局默认点击间隔时间
    public static long defDelayTime = 500;

    private final ViewClickDelayListener viewClickDelayListener;
    //最小点击间隔时间
    private final long minDelayTime;
    //上一次点击时间
    private long lastClickTime = 0;

    public ViewClickDelay(ViewClickDelayListener viewClickDelayListener, long minDelayTime) {
        this.viewClickDelayListener = viewClickDelayListener;
        this.minDelayTime = minDelayTime;
    }

    public ViewClickDelay(ViewClickDelayListener viewClickDelayListener) {
        this.viewClickDelayListener = viewClickDelayListener;
        this.minDelayTime = ViewClickDelay.defDelayTime;
    }

    @Override
    public void onClick(View v) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime > minDelayTime) {
            lastClickTime = currentTime;
            viewClickDelayListener.clickDelay(v);
        }
    }

    public interface ViewClickDelayListener {
        void clickDelay(View v);
    }

    public static void addClick(View v, ViewClickDelayListener listener) {
        v.setOnClickListener(new ViewClickDelay(listener));
    }

    public static void addClick(View v, ViewClickDelayListener listener, long delay) {
        v.setOnClickListener(new ViewClickDelay(listener, delay));
    }
}
